package com.shi.yoyoshop.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shi.yoyoshop.bean.Goods;
import com.shi.yoyoshop.bean.User;
import com.shi.yoyoshop.dto.LoginUserDto;
import com.shi.yoyoshop.dto.RegisterUserDto;
import com.shi.yoyoshop.dto.UpdateUserDto;
import com.shi.yoyoshop.service.GoodsService;
import com.shi.yoyoshop.service.OrderService;
import com.shi.yoyoshop.service.TypeService;
import com.shi.yoyoshop.service.UserService;
import com.shi.yoyoshop.util.PageUtil;
import com.shi.yoyoshop.util.SafeUtil;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class UserController {


    @Resource
    private UserService userService;

    @Resource
    private TypeService typeService;

    @Resource
    private GoodsService goodsService;

    @Resource
    private OrderService orderService;

    @GetMapping("/index/register")
    public String toRegister(HttpServletRequest request) {
        request.setAttribute("flag", 5);
        return "/index/register.jsp";
    }

    /**
     * 用户注册接口
     *
     * @param request
     * @param registerUserDto
     * @return
     */
    @PostMapping("/index/register")
    public String register(HttpServletRequest request, RegisterUserDto registerUserDto) {
        // 查询数据库中是否已经存在该用户名
        User user = null;
        user = userService.getUserByUsername(registerUserDto.getUsername());
        if (!ObjectUtils.isEmpty(user)) {
            request.setAttribute("msg", "该用户名已存在");
            return "/index/register.jsp";
        }
        user = userService.getUserByPhone(registerUserDto.getPhone());
        if (!ObjectUtils.isEmpty(user)) {
            request.setAttribute("msg", "该手机号已被注册");
            return "/index/register.jsp";
        }
        // 用户名 和 手机号 都没有被占用
        // 密码加密
        String encodePassword = SafeUtil.encode(registerUserDto.getPassword());
        user = new User(null, registerUserDto.getUsername(), encodePassword, registerUserDto.getName(), registerUserDto.getPhone(), registerUserDto.getAddress(), 1);
        userService.save(user);
        request.setAttribute("flag", 6);
        return "redirect:/index/login";
    }


    @GetMapping("/index/login")
    public String toLogin(HttpServletRequest request) {
        request.setAttribute("flag", 6);
        return "/index/login.jsp";
    }

    /**
     * 用户登录接口
     *
     * @param request
     * @param loginUserDto
     * @return
     */
    @PostMapping("/index/login")
    public String login(HttpServletRequest request, LoginUserDto loginUserDto) {

        User user = null;
        // 登录失败
        // 1. 用户名不存在的情况
        user = userService.getUserByUsername(loginUserDto.getUsername());
        if (ObjectUtils.isEmpty(user)) {
            request.setAttribute("msg", "用户名不存在");
            return "/index/login.jsp";
        }
        // 2. 密码错误的情况
        String passwordFromReq = SafeUtil.encode(loginUserDto.getPassword());
        if (!user.getPassword().equals(passwordFromReq)) {
            request.setAttribute("msg", "密码错误");
            return "/index/login.jsp";
        }
        // 登录成功
        request.getSession().setAttribute("user", user);

        // -------------------首页需要的数据重新请求-------------------
        // 今日精选推荐
        List<Goods> goodsList1 = goodsService.getGoodsListByHotTypeId(1);
        request.setAttribute("top1List", goodsList1);
        // 热销推荐
        List<Goods> goodsList2 = goodsService.getGoodsListByHotTypeId(2);
        request.setAttribute("top2List", goodsList2);
        List<Goods> goodsList3 = goodsService.getGoodsListByHotTypeId(3);
        // 新品推荐
        request.setAttribute("top3List", goodsList3);
        request.setAttribute("flag", 1);
        return "redirect:/";
    }

    @GetMapping("/index/my")
    public String my(HttpServletRequest request) {
        request.setAttribute("flag", 4);
        return "/index/my.jsp";
    }

    /**
     * 个人中心中更新用户信息
     *
     * @param request
     * @param updateUserDto
     * @return
     */
    @PostMapping("/index/my")
    public String updateMy(HttpServletRequest request, UpdateUserDto updateUserDto) {
        int type = updateUserDto.getType();
        User user = userService.getUserById(updateUserDto.getId());
        // 修改除密码外的用户信息
        if (type == 1) {
            user.setName(updateUserDto.getName());
            user.setPhone(updateUserDto.getPhone());
            user.setAddress(updateUserDto.getAddress());
            userService.updateById(user);
            request.setAttribute("msg", "更新成功");
        }
        // 修改密码
        if (type == 2) {
            // 校验旧密码是否正确
            if (user.getPassword().equals(SafeUtil.encode(updateUserDto.getPassword()))) {
                user.setPassword(SafeUtil.encode(updateUserDto.getPasswordNew()));
                userService.updateById(user);
                request.setAttribute("flag", 6);
                request.setAttribute("msg", "请登录");
                return "redirect:/index/login";
            } else {
                request.setAttribute("msg", "旧密码不正确");
            }
        }
        request.setAttribute("flag", 4);
        request.getSession().setAttribute("user", user);
        return "/index/my.jsp";

    }


    @GetMapping("/index/logout")
    public String logout(HttpServletRequest request) {
        request.getSession().invalidate();
        // 今日精选推荐
        List<Goods> goodsList1 = goodsService.getGoodsListByHotTypeId(1);
        request.setAttribute("top1List", goodsList1);
        // 热销推荐
        List<Goods> goodsList2 = goodsService.getGoodsListByHotTypeId(2);
        request.setAttribute("top2List", goodsList2);
        List<Goods> goodsList3 = goodsService.getGoodsListByHotTypeId(3);
        // 新品推荐
        request.setAttribute("top3List", goodsList3);
        request.setAttribute("flag", 1);

        return "redirect:/index/login";
    }

    @GetMapping("/index/forget")
    public String toForgetPassword() {
        return "/index/forget.jsp";
    }

    @PostMapping("/index/forget")
    public String forgetPassword(HttpServletRequest request, String username, String phone) {
        User user = null;
        user = userService.getUserByUsername(username);
        // 用户名不存在
        if (ObjectUtils.isEmpty(user)) {
            request.setAttribute("msg", "用户名不存在! ");
            return "/index/forget.jsp";
        }
        // 手机号不正确
        if (!user.getPhone().equals(phone)) {
            request.setAttribute("msg", "手机号不正确! ");
            return "/index/forget.jsp";
        }
        user.setPassword(SafeUtil.encode("123456"));
        userService.resetPasswordByUserId(user);
        request.setAttribute("msg", "密码重置成功！新密码为：123456");
        return "redirect:/index/login";
    }

    @GetMapping("/admin/userList")
    public String searchUserListWithPage(HttpServletRequest request, Integer page, Integer size) {
        IPage<User> pageInfo = userService.getUserListWithPage(new Page<User>(page, size));
        String pageTool = PageUtil.getPageTool(request, pageInfo.getTotal(), page, size);
        request.setAttribute("pageTool", pageTool);
        request.setAttribute("flag", 2);
        request.setAttribute("userList", pageInfo.getRecords());
        return "/admin/user_list.jsp";
    }

    @GetMapping("/admin/userEdit")
    public String toEditUser(HttpServletRequest request, Integer id) {
        User user = userService.getById(id);
        request.setAttribute("user", user);
        return "/admin/user_edit.jsp";
    }

    @PostMapping("/admin/userEdit")
    public String editUser(HttpServletRequest request, Integer id, String name, String phone, String address) {
        User user = new User();
        user.setId(id);
        user.setName(name);
        user.setPhone(phone);
        user.setAddress(address);
        userService.updateById(user);
        return "redirect:/admin/userList?page=1&size=6";
    }

    @GetMapping("/admin/userModifyPwd")
    public String toModifyUserPassword(HttpServletRequest request, Integer id) {
        User user = userService.getUserById(id);
        request.setAttribute("user", user);
        return "/admin/user_modifyPwd.jsp";
    }

    @PostMapping("/admin/userModifyPwd")
    public String modifyUserPassword(HttpServletRequest request, Integer id, String password) {
        User user = new User();
        user.setId(id);
        user.setPassword(SafeUtil.encode(password));
        userService.resetPasswordByUserId(user);
        return "redirect:/admin/userList?page=1&size=6";
    }

    @GetMapping("/admin/userDelete")
    public String removeUser(Integer id) {
        User user = new User();
        user.setId(id);
        user.setStatus(0);
        userService.updateById(user);
        return "redirect:/admin/userList?page=1&size=6";
    }

    @GetMapping("/admin/userAdd")
    public String toAddUser() {
        return "/admin/user_add.jsp";
    }

    @PostMapping("/admin/userAdd")
    public String addUser(HttpServletRequest request, User user) {
        User one = userService.getUserByUsername(user.getUsername());
        if (!ObjectUtils.isEmpty(one)) {
            request.setAttribute("msg", "该用户名已存在");
            return "/admin/user_add.jsp";
        }
        user.setStatus(1);
        user.setPassword(SafeUtil.encode(user.getPassword()));
        userService.save(user);
        return "redirect:/admin/userList?page=1&size=6";
    }
}
